# -*- coding: utf-8 -*-
#
# The Philatelist program is a fork of the Philatelist program
# Copyright (c) 2011 - 2024 Vitaly Ignatov (OpenNumismat) <opennumismat@gmail.com>
# Copyright (c) 2021 - 2024 Victor Nabatov (Philatelist) <nabatov.victor@gmail.com>
#

import codecs
import os.path
import ssl
import sys
import traceback

from PySide6.QtCore import QCoreApplication, QDateTime, QTranslator, QLibraryInfo, QLocale
from PySide6.QtWidgets import QApplication, QMessageBox

import Philatelist
from Philatelist.Settings import Settings
from Philatelist.MainWindow import MainWindow
from Philatelist.Tools import TemporaryDir
from Philatelist import version


def main():
    app = QApplication(sys.argv)

    QCoreApplication.setOrganizationName(version.Company)
    QCoreApplication.setApplicationName(version.AppName)

    settings = Settings()
    app.setStyle(settings['style'])
    sys.excepthook = exceptHook

    # If the program or collection images were moved to another location...
    if settings['home_path'] != Philatelist.HOME_PATH:
        settings['home_path'] = Philatelist.HOME_PATH
        import subprocess
        subprocess.run(["python3", os.path.join(Philatelist.RESOURCES_PATH, "create_reference.py")])

    TemporaryDir.init(version.AppName)
    locale = QLocale(settings['locale'])

    translator = QTranslator(app)
    if translator.load(locale, 'lang', '_', Philatelist.RESOURCES_PATH + '/i18n'):
        app.installTranslator(translator)

    path = QLibraryInfo.path(QLibraryInfo.TranslationsPath)
    translator = QTranslator(app)
    if translator.load(locale, 'qtbase', '_', path):
        app.installTranslator(translator)

    # TODO: Enable SSL verification
    ssl._create_default_https_context = ssl._create_unverified_context

    mainWindow = MainWindow()
    mainWindow.show()
    mainWindow.raise_()  # this will raise the window on Mac OS X
    mainWindow.openStartCollection()

    status = app.exec_()

    # Clear temporary files
    TemporaryDir.remove()

    sys.exit(status)


def exceptHook(type_, value, tback):
    stack = ''.join(traceback.format_exception(type_, value, tback))
    title = QApplication.translate("ExcpHook", "System error")
    text = QApplication.translate(
        "ExcpHook",
        "A system error occurred."
    )
    msgBox = QMessageBox(QMessageBox.Information, title, text)
    msgBox.setDetailedText(stack)
    msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard)
    if msgBox.exec_() == QMessageBox.Save:
        date = QDateTime.currentDateTime()
        date = QLocale.system().toString(date, QLocale.LongFormat)
        errorMessage = date + '\n' + stack
        errorlog_file = codecs.open(Philatelist.HOME_PATH + '/Philatelist_error.log', "w", "utf-8")
        errorlog_file.write(errorMessage)
        errorlog_file.close()
    # Call the default handler
    sys.__excepthook__(type_, value, tback)
